<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">评分管理</h2>
      <el-button type="primary" :icon="Refresh" @click="loadData">刷新</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="地点名称">
          <el-input
            v-model="searchForm.locationName"
            placeholder="请输入地点名称"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input
            v-model="searchForm.userNickname"
            placeholder="请输入用户昵称"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="评分">
          <el-select v-model="searchForm.score" placeholder="全部评分" clearable>
            <el-option label="5星" :value="5" />
            <el-option label="4星" :value="4" />
            <el-option label="3星" :value="3" />
            <el-option label="2星" :value="2" />
            <el-option label="1星" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Star /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ pagination.total }}</div>
            <div class="stat-label">评分总数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon avg">
            <el-icon><StarFilled /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ averageScore.toFixed(1) }}</div>
            <div class="stat-label">平均评分</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon high">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.highScores }}</div>
            <div class="stat-label">高分 (≥4星)</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon low">
            <el-icon><WarningFilled /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.lowScores }}</div>
            <div class="stat-label">低分 (≤2星)</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'createdAt', order: 'descending' }"
      >
        <el-table-column type="index" label="#" width="60" />

        <el-table-column label="地点" min-width="180">
          <template #default="{ row }">
            <div v-if="row.location" class="location-cell">
              <el-text>{{ row.location.name }}</el-text>
              <el-text type="info" size="small">ID: {{ row.locationId }}</el-text>
            </div>
            <el-text v-else type="info">未知地点</el-text>
          </template>
        </el-table-column>

        <el-table-column label="用户" min-width="180">
          <template #default="{ row }">
            <div v-if="row.user" class="user-cell">
              <el-avatar :size="32" :src="row.user.avatarUrl || undefined">
                {{ row.user.nickname?.[0] || '?' }}
              </el-avatar>
              <div class="user-text">
                <div class="nickname">{{ row.user.nickname || '匿名用户' }}</div>
                <el-text type="info" size="small">ID: {{ row.userId }}</el-text>
              </div>
            </div>
            <el-text v-else type="info">未知用户</el-text>
          </template>
        </el-table-column>

        <el-table-column label="评分" width="180">
          <template #default="{ row }">
            <div class="rating-cell">
              <el-rate v-model="row.score" disabled show-score text-color="#ff9900" />
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="评分时间" min-width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="primary"
                size="small"
                :icon="View"
                @click="handleView(row)"
              >
                详情
              </el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="评分详情"
      width="700px"
      destroy-on-close
    >
      <el-descriptions v-if="currentRating" :column="2" border>
        <el-descriptions-item label="评分ID">
          {{ currentRating.id }}
        </el-descriptions-item>
        <el-descriptions-item label="评分">
          <el-rate v-model="currentRating.score" disabled show-score text-color="#ff9900" />
        </el-descriptions-item>
        <el-descriptions-item label="地点名称" :span="2">
          {{ currentRating.location?.name || '未知地点' }}
        </el-descriptions-item>
        <el-descriptions-item label="地点ID">
          {{ currentRating.locationId }}
        </el-descriptions-item>
        <el-descriptions-item label="地点坐标">
          <el-text v-if="currentRating.location" type="info" size="small">
            X: {{ currentRating.location.coordinateX?.toFixed(6) }}, Y: {{ currentRating.location.coordinateY?.toFixed(6) }}
          </el-text>
          <el-text v-else type="info">-</el-text>
        </el-descriptions-item>
        <el-descriptions-item label="用户昵称">
          {{ currentRating.user?.nickname || '匿名用户' }}
        </el-descriptions-item>
        <el-descriptions-item label="用户ID">
          {{ currentRating.userId }}
        </el-descriptions-item>
        <el-descriptions-item label="用户头像" :span="2">
          <el-avatar v-if="currentRating.user" :size="60" :src="currentRating.user.avatarUrl || undefined">
            {{ currentRating.user.nickname?.[0] || '?' }}
          </el-avatar>
        </el-descriptions-item>
        <el-descriptions-item label="评分时间" :span="2">
          {{ formatDateTime(currentRating.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">
          {{ formatDateTime(currentRating.updatedAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Search,
  View,
  Delete,
  Star,
  StarFilled,
  TrendCharts,
  WarningFilled
} from '@element-plus/icons-vue'
import { getRatings, deleteRating } from '@/api/rating'
import type { Rating } from '@/types/api'

// 数据状态
const loading = ref(false)
const tableData = ref<Rating[]>([])
const currentRating = ref<Rating | null>(null)
const detailDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  locationName: '',
  userNickname: '',
  score: null as number | null
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 平均评分
const averageScore = computed(() => {
  if (tableData.value.length === 0) return 0
  const total = tableData.value.reduce((sum, item) => sum + item.score, 0)
  return total / tableData.value.length
})

// 统计数据
const stats = computed(() => {
  const highScores = tableData.value.filter((item) => item.score >= 4).length
  const lowScores = tableData.value.filter((item) => item.score <= 2).length
  return {
    highScores,
    lowScores
  }
})

/**
 * 加载数据
 */
async function loadData() {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      limit: pagination.limit
    }

    const response = await getRatings(params)

    if (response.success) {
      // 过滤搜索条件
      let filteredData = response.data

      if (searchForm.locationName) {
        filteredData = filteredData.filter((item) =>
          item.location?.name.toLowerCase().includes(searchForm.locationName.toLowerCase())
        )
      }

      if (searchForm.userNickname) {
        filteredData = filteredData.filter((item) =>
          item.user?.nickname?.toLowerCase().includes(searchForm.userNickname.toLowerCase())
        )
      }

      if (searchForm.score !== null) {
        filteredData = filteredData.filter((item) => item.score === searchForm.score)
      }

      tableData.value = filteredData
      pagination.total = response.pagination.total
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索
 */
function handleSearch() {
  pagination.page = 1
  loadData()
}

/**
 * 重置搜索
 */
function handleReset() {
  searchForm.locationName = ''
  searchForm.userNickname = ''
  searchForm.score = null
  pagination.page = 1
  loadData()
}

/**
 * 查看详情
 */
function handleView(rating: Rating) {
  currentRating.value = rating
  detailDialogVisible.value = true
}

/**
 * 删除
 */
async function handleDelete(rating: Rating) {
  try {
    const locationName = rating.location?.name || '未知地点'
    const userName = rating.user?.nickname || '匿名用户'

    await ElMessageBox.confirm(
      `确定要删除用户"${userName}"对"${locationName}"的评分吗？删除后将无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    loading.value = true
    const response = await deleteRating(rating.id)

    if (response.success) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 页码改变
 */
function handlePageChange(page: number) {
  pagination.page = page
  loadData()
}

/**
 * 每页数量改变
 */
function handleSizeChange(size: number) {
  pagination.limit = size
  pagination.page = 1
  loadData()
}

/**
 * 格式化日期时间
 */
function formatDateTime(dateString: string) {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.page-container {
  background: transparent;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.stat-icon.avg {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: #fff;
}

.stat-icon.high {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: #fff;
}

.stat-icon.low {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: #fff;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 表格样式 */
.location-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-text {
  flex: 1;
}

.nickname {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.rating-cell {
  display: flex;
  align-items: center;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
